package test;

import java.util.Arrays;

public class UnionFindSet {
    public int[] elem;
    public int usedsize;

    public UnionFindSet(int n) {
        this.elem = new int[n];
        Arrays.fill(elem, -1);
    }

    //查询x的根节点
    public int findRoot(int x) {
        if (x < 0) {
            throw new IndexOutOfBoundsException("下标不合法，是负数");
        }
        while (elem[x] >= 0) {
            x = elem[x];
        }
        return x;
    }

    //查询x y 是不是同一个集合
    public boolean isSameUnionFindSet(int x, int y) {
        int index1 = findRoot(x);
        int index2 = findRoot(y);
        if (index1 == index2) {
            return true;
        }
        return false;
    }

    //合并
    public void union(int x, int y) {
        int index1 = findRoot(x);
        int index2 = findRoot(y);
        if (index1 == index2) {
            return;
        }
        elem[index1] = elem[index1] + elem[index2];
        elem[index2] = index1;
    }

    //
    public int getCount() {
        int count = 0;
        for (int x : elem) {
            if (x < 0) {
                count++;
            }
        }
        return count;
    }

    public void print() {
        for (int x : elem) {
            System.out.print(x + " ");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        UnionFindSet unionFindSet = new UnionFindSet(10);
        unionFindSet.union(0, 6);
        unionFindSet.union(0, 1);
        unionFindSet.union(3, 7);
        unionFindSet.union(4, 8);
        System.out.println("以下是不是亲戚？");
        boolean flg = unionFindSet.isSameUnionFindSet(1, 6);
        if (flg) {
            System.out.println("是亲戚");
        } else {
            System.out.println("不是亲戚");
        }
    }
}
